package com.lamda.zhekou;

import com.bethecoder.ascii_table.ASCIITable;
import com.bethecoder.ascii_table.ASCIITableHeader;
import com.lamda.zhekou.config.ApplicationSettings;
import com.lamda.zhekou.manager.WorkerManager;
import com.lamda.zhekou.master.MasterServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * Created by MJiao on 11/17/14.
 */
@EnableConfigurationProperties
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableJpaRepositories
public class ZheKouApplication {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZheKouApplication.class);

    private static ConfigurableApplicationContext configurableApplicationContext;

    public static ConfigurableApplicationContext getConfigurableApplicationContext() {
        return configurableApplicationContext;
    }


    public static void main(String[] args) {

        LOGGER.info("WebServerApplication is starting ...");

        String current = null;
        try {
            current = new java.io.File(".").getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String currentDir = System.getProperty("user.dir");

        LOGGER.info("Current dir:" + current);
        LOGGER.info("Current dir using System(user.dir):" + currentDir);

        ZheKouApplication.configurableApplicationContext = SpringApplication.run(ZheKouApplication.class, args);

        LOGGER.info("WebServerApplication start successfully !");

        configurableApplicationContext.getBean(MasterServer.class).run();
        configurableApplicationContext.getBean(WorkerManager.class).ready();

        LOGGER.info("MasterServerApplication is starting ...");

        LOGGER.info("MasterServerApplication start successfully !");


      //  ZheKouApplication.getConfigurableApplicationContext().getBean(TaskExecutorCenter.class).prepare();

        LOGGER.info("TaskExecutorCenter prepare successfully !");

        ZheKouApplication.printApplicationSetting(configurableApplicationContext);

    }

    /**
     * 打印应用相关配置参数
     *
     * @param configurableApplicationContext
     */
    private static void printApplicationSetting(ConfigurableApplicationContext configurableApplicationContext) {

        ApplicationSettings applicationSettings = configurableApplicationContext.getBean(ApplicationSettings.class);
        String applicationName = configurableApplicationContext.getApplicationName();

        Field[] fields = applicationSettings.getClass().getDeclaredFields();

        ASCIITableHeader[] headerObjs = {
                new ASCIITableHeader("Key", ASCIITable.ALIGN_LEFT),

                new ASCIITableHeader("Value", ASCIITable.ALIGN_LEFT),
        };


        for (Field f : fields) {
            f.setAccessible(true);
        }

        String[][] data = new String[fields.length + 1][];
        data[0] = new String[]{"applicationName", applicationName};

        for (int index = 0; index < fields.length; index++) {
            Field field = fields[index];
            try {
                String[] details = {field.getName(), field.get(applicationSettings).toString()};
                data[index + 1] = details;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        LOGGER.info(new StringBuffer("\n").append(ASCIITable.getInstance().getTable(headerObjs, data)).toString());
    }
}
